package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go.web.demo.com/web/model"
	"runtime"
)

// StackTrace 获取堆栈信息
func StackTrace() string {
	var buf [4096]byte
	n := runtime.Stack(buf[:], false)
	return fmt.Sprintf("==> %s\n", string(buf[:n]))
}

// ErrorHandle 统一处理错误中间件
func ErrorHandle() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			err := recover()
			if err != nil {
				logrus.Error("错误捕捉:", err, "\n堆栈信息:", StackTrace())
				c.JSON(200, model.ServerError("内部异常"))
			}
		}()

		c.Next() //执行下一个中间件

	}
}
